package org.big.kafkafinancesimulator.simulator;

import org.big.kafkafinancesimulator.model.TradeRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
@RequestMapping("/api/trade")
public class TradeController {
    private static final String TOPIC_TRADE_REQUESTS = "trade-requests";

    private final KafkaTemplate<String, Object> kafkaTemplate;

    public TradeController(KafkaTemplate<String, Object> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    @PostMapping("/order")
    public ResponseEntity<String> placeOrder(@RequestBody TradeRequest tradeRequest) {
        tradeRequest.setRequestId(UUID.randomUUID().toString());
        tradeRequest.setTimestamp(System.currentTimeMillis());

        // 将交易请求发送到Kafka，由后端的交易处理器进行实际处理
        kafkaTemplate.send(TOPIC_TRADE_REQUESTS, tradeRequest.getUserId(), tradeRequest);

        return ResponseEntity.accepted().body("交易请求已接受，处理中。请求ID: " + tradeRequest.getRequestId());
    }
}